import axios from 'axios'
import qs from 'qs'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create( {
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 2000 // request timeout
} )

// request interceptor
service.interceptors.request.use(
    config => {
        if( store.getters.token ) 
        {
            config.headers[ 'Authorization' ] = 'Bearer ' + getToken()
        }

        if( store.getters.csrf_token )
        {
            config.headers[ 'X-CSRF-TOKEN' ] = store.getters.csrf_token;
        }
        
        // config.headers[ 'Content-Type' ] = 'application/x-www-form-urlencoded';
        config.headers[ 'x-requested-with' ] = 'XMLHttpRequest';
        config.transformRequest = [ 
            data => {
                return qs.stringify( data ); 
            } 
        ];
        return config
    },
    error => {
        return Promise.reject( error )
    }
)

// response interceptor
service.interceptors.response.use(

    response => {
        const result = response.data;

        //10000 document not found
        if( result.code == 10000 )
        {
            Message( {
                message: '网络请求失败',
                type: 'error',
                duration: 5 * 1000
            } )
            return Promise.reject();
        }

        //10001 error data
        if( result.code == 10001 )
        {
            Message( {
                message: result.data || '错误的数据',
                type: 'error',
                duration: 5 * 1000
            } )
            return Promise.reject();
        }

        //10002 permission denied
        if( result.code == 10002 || result.code == 10003 || result.code == 10004 )
        {
            MessageBox.confirm('您需要登录系统才能进行操作', '登录提示', {
                confirmButtonText: '确定',
                type: 'warning'
            } )
            // .then( () => {
            //     store.dispatch( 'user/resetToken' ).then( () => {
            //         location.reload()
            //     } )
            // } )
            store.dispatch( 'user/resetToken' );
            return Promise.reject();
        }

        //其他
        if( result.code != 0 )
        {
            return Promise.reject( new Error( result.data || '未知错误' ) );
        }

        return result;
    },
    error => {
        console.log( error ); //debug
        let message = error;
        if( typeof error.response == 'undefined' )
        {
            message = '网络请求失败,请重试';
        }
        return Promise.reject( message )
    }
)

export default service